#!/usr/bin/env escript
%% -*- erlang-indent-level: 4; indent-tabs-mode: nil -*-

-mode(compile).

%% See https://hexdocs.pm/argparse/
%% Argparse supports a hierarchical structure of commands and subcommands, each
%% with its own arguments. This spec (no command specified) describes the top level.
%%
%% We only provide the user-level arguments. The node connection arguments, which
%% are automatically provided by the script wrappers, are specified in aeu_ext_scripts.erl
spec() -> #{ commands => cmds()
           , arguments => [ #{ name => 'timeout'
                             , short => $t
                             , help => "Timeout when waiting for mode change"
                             , type => {int, [{min, 0}]}
                             , default => 10000 }
                          ] }.

cmds() ->
    #{ "on" => #{ help => "Enable maintenance mode" }
     , "off" => #{ help => "Disable maintenance mode" }
     , "status" => #{ help => "Check maintenance mode status. Returns on | off" } }.

main(Args) ->
    Opts = aeu_ext_scripts:parse_opts(Args, spec(), #{progname => maintenance}),
    {ok, Node} = aeu_ext_scripts:connect_node(Opts),
    case Opts of
        #{cmd_spec := {["on"], _}, opts := #{'timeout' := Timeout}} ->
            set_mode(maintenance, Node, Timeout);
        #{cmd_spec := {["off"], _}, opts := #{'timeout' := Timeout}} ->
            set_mode(normal, Node, Timeout);
        #{cmd_spec := {["status"], _}} ->
            get_mode(Node)
    end.


set_mode(Mode, Node, Timeout) ->
    case rpc:call(Node, app_ctrl, set_and_await_mode, [Mode, Timeout]) of
        {ok, _} ->
            erlang:halt(0);
        {timeout, Remaining} ->
            io:format(standard_error, "TIMEOUT - Remaining: ~p~n", [Remaining]),
            erlang:halt(-1)
    end.

get_mode(Node) ->
    Res = rpc:call(Node, app_ctrl, get_mode, []),
    Output = case Res of
                 maintenance -> on;
                 _ -> off
             end,
    io:fwrite("~p~n", [Output]),
    erlang:halt(0).
